﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaskelot.SP.Model.Client;
using Kaskelot.SP.Model.Client.Forms;
using Stockholm.SOA.Kaskelot.WCF.DataContracts;

namespace Kaskelot.SP.Services.Client.Mapping
{
    public static class ClientBlankettExtensions
    {
        public static ClientBlankett ToClientContract(this Blankett entity)
        {
            ClientBlankett b = new ClientBlankett();

            CopyFromEntity(entity, b, false);

            return b;
        }

        public static ClientBlankett ToMinimalClientContract(this Blankett entity)
        {
            ClientBlankett b = new ClientBlankett();

            CopyFromEntity(entity, b, true);

            return b;
        }

        public static Blankett ToContract(this ClientBlankett b)
        {
            Blankett entity = new Blankett();

            CopyToEntity(b, entity);

            return entity;
        }

        public static Blankett UpdateContract(this Blankett blankett, BlankettForm form)
        {
            if (blankett.Id == Guid.Empty)
            {
                blankett.Id = Guid.NewGuid();
            }

            blankett.Namn = form.Namn;
            blankett.Andrad = form.Andrad;
            blankett.AndradAv = form.AndradAv;
            blankett.Typ = (BlankettTyp) form.BlankettTyp;

            return blankett;
        }

        private static void CopyFromEntity(Blankett from, ClientBlankett to, bool minimal)
        {
            to.Id = from.Id;
            to.ValId = from.ValId;
            to.Namn = from.Namn;
            to.Andrad = from.Andrad != null ? from.Andrad.ToString() : null;
            to.AndradAv = from.AndradAv;
            to.Skapad = from.Skapad != null ? from.Skapad.ToString() : null;
            to.SkapadAv = from.SkapadAv;
            to.BlankettTyp = from.Typ.ToString();
        }

        private static void CopyToEntity(ClientBlankett from, Blankett to)
        {
            to.Id = from.Id;
            to.ValId = from.ValId;
            to.Namn = from.Namn;

            if (!String.IsNullOrEmpty(from.Andrad))
                to.Andrad = DateTime.Parse(from.Andrad);
            else
                to.Andrad = null;

            to.AndradAv = from.AndradAv;

            if (from.Skapad != null)
                to.Skapad = DateTime.Parse(from.Skapad);

            to.SkapadAv = from.SkapadAv;

            to.Typ = (BlankettTyp)Enum.Parse(typeof(BlankettTyp), from.BlankettTyp);
        }
    }
}
